from exts import db
from datetime import datetime


class CommentModel(db.Model):
    __tablename__ = 'comment'
    # 评论id
    comment_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 评论用户id
    comment_user_id = db.Column(db.String(32), db.ForeignKey("user.open_id"))
    # 博客id
    comment_blog_id = db.Column(db.Integer, db.ForeignKey("blog.blog_id"))
    # 内容
    content = db.Column(db.String(200), default="", nullable=False)
    # 评论创建时间
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now)

    # 关系
    user = db.relationship('UserModel', back_populates='comments')
    blog = db.relationship('BlogModel', back_populates='comments')

    def to_dict(self):
        blind = ('comment_user_id', )
        return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns if c.name not in blind}

    @staticmethod
    def _convert_value(value):
        if isinstance(value, datetime):
            return int(value.timestamp() * 1000)  # 转换为毫秒级时间戳
        return value
